/**
* Creat By liyuanquan 2017/1/17
**/
var operate = 0;
// 弹出层相关索引
var showLayerIndex = 0;
// 相关路径
var resetToolUrl = serverPath + "weighing/zeroClearing";
var checkWeighResultUrl = serverPath + "weighing/findWeighingResult";

$(function() {
	init();
	// 点击上一步按钮 事件
	$("#preBtn").click(function(){
		var step = $('#stepNavBar a.step');
		var thisParent = $('#stepNavBar a.step').parent("li");

		step.removeClass("step"); // 删除其他兄弟元素的样式
		thisParent.prev("li").prev("li").children("a").addClass("step"); // 添加当前元素的样式
		nowStep();
		initBtn();
	});
	// 点击下一步按钮 事件
	$("#nextBtn").click(function(){
		var step = $('#stepNavBar a.step');
		var thisParent = $('#stepNavBar a.step').parent("li");

		step.removeClass("step"); // 删除其他兄弟元素的样式
		thisParent.next("li").next("li").children("a").addClass("step"); // 添加当前元素的样式
		nowStep();
		initBtn();
		$("#nextBtn").attr("disabled",true);
	});
	// 称量结果按钮 事件
	$("#resultBtn").click(function() {
		var url = "weighResult.html";
		showLayerIndex = ibcpLayer.ShowDiv(url,'称量结果','750px','410px',function() {
			$('#weighResultList').bootstrapTable();
			// 查询称量结果
			var materialCode = $("#leftSide #materialCode").text();
			var materialName = $("#leftSide #materialName").text();
			var theoreQuantity = $("#rightSide #theoreQuantity").text();

			$("#materialResultCode").text(materialCode);
			$("#materialCodeName").text(materialName);
			$("#theoreticalQuanity").text(theoreQuantity);

			var orderId = weighing.orderId;
			var bomDetailId = weighing.bomDetailId;
			var orderBomId = weighing.orderBomId;

			weightingResult(orderId,bomDetailId,orderBomId);
			// 称量结果取消按钮 事件
			$("#weighResultCancel").click(function() {
				ibcpLayer.Close(cancelEvent());
			});
		});
	});

	$("#operateBtn").click(function() {
		var operateBtn = $("#operateBtn").attr("operate");
		var weighingMode = $("#weighingMode").text();

		//选择批指令操作
		if(operateBtn == 1){
			var url = "WeighingSelectOrder.html";
			showLayerIndex = ibcpLayer.ShowDiv(url, '选择批指令', '1000px', '520px',function() {
				GetWorkCenterOrders();

				$("#selectOrderEnsure").click(function(){
					var selectedOrder = $('#SelectOrderTable').bootstrapTable('getSelections')[0];
					if(selectedOrder == undefined) return;

					$('#btcInstructionNum').text(selectedOrder.batchNo);
					$('#matCode').text(selectedOrder.matCode);
					$('#matName').text(selectedOrder.mName);
					$('#planData').text(selectedOrder.planDate);
					$('#optionNum').text(selectedOrder.code);
					$('#batchNum').text(selectedOrder.batchNo);
					$('#standard').text(selectedOrder.mSpec);
					$('#planBatch').text(selectedOrder.planQuantity + "(" + selectedOrder.uomName + ")");

					weighing.orderId =  selectedOrder.orderId;
					weighing.operationId = selectedOrder.operationId;
					weighing.workCenterId = selectedOrder.workCenterId;
					weighing.workCenterOrderId = selectedOrder.id;

					cancelEvent();
					// 完成本步骤 下一步 按钮可用
					$("#nextBtn").attr("disabled",false);
				})

				$("#cancelOrderBtn").click(function(){
					cancelEvent();
				})
			});
		}

		//选择BOM操作
		if(operateBtn == 2){
			var url = "WeighingSelectBOMMat.html";
			showLayerIndex = ibcpLayer.ShowDiv(url, '选择物料项', '600px', '400px',function() {
				GetBomMaterial();

				$("#selectBOMMatEnsure").click(function(){
					var selectedMat = $('#SelectBOMMatTable').bootstrapTable('getSelections')[0];
					if(selectedMat == undefined) return;

					$('#BomItemCode').text(selectedMat.itemCode);
					$('#materialCode').text(selectedMat.materialCode);
					$('#materialName').text(selectedMat.materialName);
					//$('#weighingMode').text(selectedMat.quantity);
					$('#toleranceLower').text(selectedMat.toleranceLower);
					$('#toleranceUpper').text(selectedMat.toleranceUpper);
					$("#weighingMode").text(selectedMat.weightModeName);

					weighing.orderBomId = selectedMat.orderBomId;
					weighing.bomDetailId = selectedMat.id;
					weighing.weightModeId = selectedMat.weightModeId;
					weighing.toleranceLower = selectedMat.toleranceLower;
					weighing.toleranceUpper = selectedMat.toleranceUpper;
					weighing.toleranceTypeId = selectedMat.toleranceTypeId;

					cancelEvent();
					// 完成本步骤 下一步 按钮可用
					$("#nextBtn").attr("disabled",false);
				})

				$("#cancelBOMMatBtn").click(function(){
					cancelEvent();
				})
			});
		}

		//选择物料批次操作
		if(operateBtn == 3){
			ibcpLayer.ShowConfirm('确定要执行此操作指令吗？', function(){
				ExecuteWorkCenterOrder();
			});
		}

		//选择称量模式操作
		if(operateBtn == 4) {
			var url = "selectWeighMode.html";
			showLayerIndex = ibcpLayer.ShowDiv(url, '选择称量模式', '400px', '320px',function() {
				//确认选择按钮
				$('#seleWeighModeConfirm').click(function(){
					seleWeighModeConfirm();
					// 完成本步骤 下一步 按钮可用
					$("#nextBtn").attr("disabled",false);
				})
				//取消选择按钮
				$('#seleWeighModeCancel').click(function(){
					cancelEvent();
				})
			});
		};

		//选择称具操作
		if(operateBtn == 5) {
			var url = "selectWeighTool.html";
			showLayerIndex = ibcpLayer.ShowDiv(url,'选择称具','750px','455px',function() {
				GetWeighTool();
				// 选择称具确认按钮 事件
				$("#seleWeighToolConfirm").click(function() {
					//选择称具确认
					SelectWeighToolEnsure();
				});
				// 选择称具取消按钮 事件
				$("#seleWeighToolCancel").click(function() {
					cancelEvent();
				});
			});
		};

		if(operateBtn == 6) {
			resetToolConfirm();
		};

		if(operateBtn == 7 && weighingMode == "净重称量") {
			var netWeightingPath = serverPath + "weighing/weighingTare";
			var mchData = {"id": 116};
			//调用后端去皮接口
			ibcpAjax.Update(netWeightingPath, mchData, true, function(result){
				var datas = result.data;
				$('#tare').html(datas);
				ibcpLayer.ShowConfirm('去皮成功', function(){
					//resetConfirm();
					$("#nextBtn").attr("disabled",false);
				});
			});
		}

		if(operateBtn == 7 && weighingMode !== "净重称量") {
			var url = 'NetWeighting.html';
			showLayerIndex = ibcpLayer.ShowDiv(url,'称量皮重', '550px', '200px',function(){
				//去皮确认
				$('#Net_Weighting_Confirm').on('click', function(){
					//非空验证
					if($('#Net_Weight_Get').val() == ""){
						ibcpLayer.ShowTips("请录入皮重！", $('#Net_Weight_Get'));
						return;
					}
					$('#tare').html($('#Net_Weight_Get').val());
					ibcpLayer.Close(showLayerIndex);
				});
			});
		}

		if(operateBtn == 8) {
			weighFinish();
			//var url = "weighFinish.html";
			//showLayerIndex = ibcpLayer.ShowDiv(url,'称量结束','650px','635px',function() {
			//	$('#weighFinishList').bootstrapTable();
			//	// 点击乘凉结束步骤按钮 事件
			//	weighFinish();
			//	// 选择称具取消按钮 事件
			//	$("#weighFinishCancel").click(function() {
			//		cancelEvent();
			//	});
			//});
		};
	});
});

//全局属性
var weighing = new Object({
	orderId : -1,//指令id
	workCenterId : -1,//工位id
	workCenterOrderId : -1,//工位指令id
	bomDetailId : -1,//BOM物料项id
	orderBomId : -1,//指令Bom id
	operationId : -1,//操作id
	weightModeId : -1,//称量模式id
	batchId : -1,//批次id
	equipmentId : -1,//称具id
	tag : undefined,//tag值，实时获取称的数据
	theoreticalWeight : 0,//理论数量
	targetWeight : 0,//计算数量
	toleranceLower : 0,//误差下限
	toleranceUpper : 0,//误差上限
	toleranceTypeId : -1//误差类型
});

function init() {
	nowStep();
	initBtn();
};

function count() {
	var theoreQuantity = $('#theoreQuantity').val();
	var countQuantity = $('#countQuantity').val();
	var error = $('#error').val();

	var percent = Math.floor(((countQuantity - error)/theoreQuantity)*100);

	$('#progressbar').removeClass();

	if(percent >= 0 && percent < 60) {
		$('#progressbar').addClass("progress-bar progress-bar-info");
		$('#progressbar').attr("aria-valuenow",percent);
		$('#progressbar').css("width",percent + 1 + "%");
		$('#progressbar span').text(countQuantity + " 量不足");

		$("#message span").text("称量少于目标范围!");
	}else if (percent >= 60 && percent <= 70) {
		$('#progressbar').addClass("progress-bar progress-bar-success");
		$('#progressbar').attr("aria-valuenow",percent);
		$('#progressbar').css("width",percent + 1 + "%");
		$('#progressbar span').text(countQuantity + " 量足够");
	}else if (percent > 70 && percent <= 100) {
		$('#progressbar').addClass("progress-bar progress-bar-danger");
		$('#progressbar').attr("aria-valuenow",percent);
		$('#progressbar').css("width",percent + 1 + "%");
		$('#progressbar span').text(countQuantity + " 量超标");

		$("#message span").text("称量超过目标范围!");
	}else {
		$('#progressbar').addClass("progress-bar progress-bar-danger");
		$('#progressbar').attr("aria-valuenow",percent);
		$('#progressbar').css("width","100%");
		$('#progressbar span').text(countQuantity + " 量远远超标");
	}
};

// 更换操作按钮显示文字和标识状态
function nowStep() {
	var nowStep = $("#stepNavBar a.step").text();
	var weighingMode = $("#weighingMode").text();
	var nowOperate = $("#stepNavBar a.step").parent("li").attr("operate");
	// 操作按钮显示当前步骤
	if(nowOperate == 8) {
		$("#nowStep span").text("称量结束");
		$("#operateBtn").attr("operate",nowOperate);
	}if(nowOperate == 7 && weighingMode == "净重称量"){
		$("#nowStep span").text("去皮");
		$("#operateBtn").attr("operate",nowOperate);
	}else {
		$("#nowStep span").text(nowStep);
		$("#operateBtn").attr("operate",nowOperate);
	}
	// 操作按钮标识状态
	if(nowOperate == 8) {
		$("#nowStep #operateBtn").removeClass("btn-success");
		$("#nowStep #operateBtn").addClass("btn-danger");
	}else {
		$("#nowStep #operateBtn").removeClass("btn-danger");
		$("#nowStep #operateBtn").addClass("btn-success");
	};
};
// 当到达第一步时，上一步按钮不可以 当到达最后一步时，下一步按钮不可用
function initBtn() {
	var firstStep = $("#stepNavBar li#firstStep a").hasClass("step");

	if(firstStep == true) {
		$("#preBtn").attr("disabled",true);
	}else {
		$("#preBtn").attr("disabled",false);
	};
};
/************************************************* 选择按钮 事件 & 方法 *******************************************/
// 查看批指令称量结果
function weightingResult(orderId,bomDetailId,orderBomId) {
	var datas = {"orderId": orderId,"bomDetailId": bomDetailId,"orderBomId": orderBomId};
	ibcpAjax.Select(checkWeighResultUrl,datas,true,function(result) {
		$("#weighResultList").bootstrapTable("load",result);
	});
};
//格式化操作列
function operateFormatter(value,row,index){
	return[
		'<div>',
		'<a class="like" href="javascript:void(0)" title="打印">',
		'<i class="glyphicon glyphicon-print"></i>',
		'</a>',
		'</div>'
	].join('');
}

//操作列事件
window.operateEvents = {
	'click .like': function (e, value, row, index) {
		PrintWHLabel(JSON.stringify(row));
	}
}
// 选择称量模式确认按钮 事件
function seleWeighModeConfirm() {
	var selectedMode = $('#weighingModeTable').bootstrapTable('getSelections')[0];
	if(selectedMode){
		$('#weighingMode').text(selectedMode.name);
		$('#weighingMode').attr('modeId',selectedMode.id);
		cancelEvent();
	}
};

// 称具清零确认按钮 事件
function resetToolConfirm() {
	ibcpLayer.ShowConfirm('您确认要清零称具吗？', function(){
		var equipmentId = weighing.equipmentId;
		resetConfirm(equipmentId);
	});
};
// 确定清零后调取后台签名
function resetConfirm(selectedDelId){
	CallSign(100,function() {
		var datas = {'id':selectedDelId};
		ibcpAjax.Update(resetToolUrl,datas,true,function(){
			ibcpLayer.ShowOK('清零成功！');
			// 签名层消失
			SignCancel();
			// 完成本步骤 下一步 按钮可用
			$("#nextBtn").attr("disabled",false);
		});
	});
};
// 称量结束按钮 事件
function weighFinish() {
	// toleranceTypeId 1是绝对值 2是百分比
	var toleranceTypeId = weighing.toleranceTypeId;
	console.log(toleranceTypeId);
	//var error = $("#progressbar span").val();
	//console.log(error);
	var error = 1;
	var toleranceLower = $("#toleranceLower").text();
	var toleranceUpper = $("#toleranceUpper").text();
	//var quantity = $("#progressbar").attr("aria-valuenow");
	//console.log(quantity);
	var quantity = 5.2;
	var endSign;
	if(toleranceTypeId == 1) {
		if(error >= -toleranceLower && error <= toleranceUpper) {
			endSign = 1;
			showResult(endSign,quantity);
		}else {
			endSign = 2;
			showResult(endSign,quantity);
		}
	}
	if(toleranceTypeId == 2) {
		if(error > -toleranceLower && error < toleranceUpper) {
			endSign = 1;
			showResult(endSign,quantity);
		}else {
			endSign = 2;
			showResult(endSign,quantity);
		}
	}
};
function showResult(endSign,quantity) {
	CallSign(100,function(sid){
		var finishiWeighUrl = serverPath + "weighing/endWeighing";
		var datas = {
			"wkcOrderId": weighing.workCenterOrderId,
			"bomDetailId": weighing.bomDetailId,
			"batchId": weighing.batchId,
			"endSign":endSign,
			"quantity":quantity,
			"sid":sid
		};
		//console.log(datas);
		ibcpAjax.Select(finishiWeighUrl,datas,true,function(result) {
			ibcpLayer.ShowOK('称量结束！');
			var data = result.data;
			var resultId = data.id;
			console.log(resultId);
			PrintWHLabel(resultId,sid);
			SignCancel();
		});
	})
}

// 取消按钮 事件
function cancelEvent() {
	ibcpLayer.Close(showLayerIndex);
};

/************************************************* 获取批指令 *******************************************/
//获取批指令
function GetWorkCenterOrders(){
	var param = '';
	var url = serverPath + "workCenterOrder/findWorkCenterOrderByWorkCenterId";
	ibcpAjax.Select(url,param,true,function(result){
		var data = result.data;
		$('#SelectOrderTable').bootstrapTable();
		$('#SelectOrderTable').bootstrapTable('load',data);
	});
}

/************************************************* 获取BOM *******************************************/
function GetBomMaterial(){
	var param = {"orderId":weighing.orderId,"operationId":weighing.operationId};
	var url = serverPath + "BomsDetail/findBomDetailByOrderIdAndOperationId";
	ibcpAjax.Select(url,param,true,function(result){
		var data = result.data;
		console.log(result);
		$("#SelectBOMMatTable").bootstrapTable();
		$('#SelectBOMMatTable').bootstrapTable('load',data);
	});
}

/************************************************* 获取批次 *******************************************/

//物料批次画面
function ShowMaterialBatch(){
	var url = "WeighingSelectMatBatch.html";
	showLayerIndex = ibcpLayer.ShowDiv(url, '选择物料批次', '480px', '490px',function() {

		var code = $('#materialCode').text();
		var name = $('#materialName').text();
		var quan = $('#theoreQuantity').text();
		$('#thisMatCode').text(code);
		$('#thisMatName').text(name);
		$('#thisBatchQuan').text(quan);

		//扫码
		$("#btnBarCode").click(function(){
			GetMaterialBatchByBarCode();
		})
		//确认选择按钮
		$('#seleMatBatchConfirm').click(function(){
			if($("#barCodeInput").val()== ''){
				ibcpLayer.ShowTips("请输入或者扫码！",$('#barCodeInput'));
				return;
			}
			SelectMaterialEnsure()
		})
		//取消选择按钮
		$('#seleMatBatchCancel').click(function(){
			cancelEvent();
		})
	});

}

//扫描获取包装信息
function GetMaterialBatchByBarCode(){
	var barCode = $("#barCodeInput").val();
	barCode = "WH170200001";
	var param = {"barcode":barCode};
	var url = serverPath + "weighing/findMaterialBatchByBarcode";
	ibcpAjax.Select(url,param,true,function(result){
		var data = result.data;
		$('#validMatBatch').text(data.batchNo);
		$("#validMatNum").text(data.seqNo);
		$('#validBatchCode').text(data.materialCode);
		$('#validBatchQuan').text(data.quantity + "(" + data.symbol + ")");
		$('#calculateQuantity').text(data.calculateQuantity);
		$('#getPurity').text(data.purity);
		$('#validMatNum').attr('packageId', data.packageId);
		weighing.batchId = data.batchId;
	});
}

//选择包装确认
function SelectMaterialEnsure(){
	var packageId = $('#validMatNum').attr('packageId');
	var param = {"orderId":weighing.orderId,"bomDetailId":weighing.bomDetailId,"packageId":packageId,"batchId":weighing.batchId};
	var url = serverPath + "weighing/validateMaterialBatch";
	ibcpAjax.Select(url,param,true,function(result){
		$('#materialBatch').text($("#validMatBatch").text());
		$("#purity").text($("#getPurity").text());
		cancelEvent();

		//获取称量目标
		GetWeighingTarget()
		// 完成本步骤 下一步 按钮可用
		$("#nextBtn").attr("disabled",false);
	});
}

/************************************************* 获取称具 *******************************************/
//获取称具
function GetWeighTool(){
	$("#SelectApplianceTable").bootstrapTable();
	var param = {"orderId":weighing.orderId,"bomDetailId":weighing.bomDetailId,"workcenterId":weighing.workCenterId};
	var url = serverPath + "weighing/findAllweighingAppliance";
	ibcpAjax.Select(url,param,true,function(result){
		var data = result.data;
		$('#SelectApplianceTable').bootstrapTable('load',data);
	});
}

//确认选择称具
function SelectWeighToolEnsure(){
	var selected = $("#SelectApplianceTable").bootstrapTable('getSelections')[0];
	if(selected == undefined) return;
	var equipmentId = selected.id;
	var param = {"orderId":weighing.orderId,"bomDetailId":weighing.bomDetailId,"equipmentId":equipmentId};
	var url = serverPath + "weighing/setWeightAppliance";
	ibcpAjax.Select(url,param,true,function(result){
		weighing.tag = result.data;
		SetWeighToolInfo(selected);
		cancelEvent();
		GetPackageList();
		$("#nextBtn").attr("disabled",false);
		//定时刷新称具数据
		self.setInterval("GetWeightApplianceNumber()",3000);
	});
}

//设置称具信息
function SetWeighToolInfo(equipment){
	weighing.equipmentId = equipment.id;
	$('#equipmentCode').text(equipment.no);
	$('#minimumRange').text(equipment.minimumRange);
	$('#ultimateRange').text(equipment.ultimateRange);
	$('#precisionValue').text(equipment.precision);
}

//获取包装信息
function GetPackageList(){
	var param = {"orderId":weighing.orderId,"bomDetailId":weighing.bomDetailId};
	var url = serverPath + "weighing/findPackageListDetail";
	ibcpAjax.Select(url,param,true,function(result){
		var data = result.data;
		$('#packageList').bootstrapTable('load',data);

		if(data.length > 0){
			$("#theoreticalWeightSum").text(data[data.length-1].theoreticalWeightSum);
			$("#actualWeightSum").text(data[data.length-1].actualWeightSum);
		}
	});
}

//执行操作指令
function ExecuteWorkCenterOrder(){
	CallSign(100,function(sid){
		var param = {"orderId":weighing.orderId,"workCenterOrderId":weighing.workCenterOrderId,"sid":sid};
		var url = serverPath + "workCenterOrder/executeWorkCenterOrder";
		ibcpAjax.Update(url,param,true,function(result){
			SignCancel();
			ShowMaterialBatch();
		});
	})
}

//获取称的读数
function GetWeightApplianceNumber(){
	var param = {"tagName":weighing.tag};
	var url = serverPath + "dataOperation/getSnapshotData";
	$.ajax({
		url: url,
		data: param,
		type: 'get',
		traditional: true,
		xhrFields:{ withCredentials:true},
		dataType: "json",
		async: true,        //默认为ture表示异步，false同步--ajax的回调方法中弱还需要掉用其他ajax方法 必须false
		success: function (result) {
			var value = result.data.value;
			//console.log(value);
		},
		error: function () {
			ibcpLayer.ShowMsg('通讯异常!');
		}
	});
}

//获取称量目标
function GetWeighingTarget() {
	var param = {"orderBomId": weighing.orderBomId, "orderId": weighing.orderId, "bomDetailId": weighing.bomDetailId};
	var url = serverPath + "weighing/calculateSurplusTargetWeight";
	ibcpAjax.Select(url, param, true, function (result) {
		var data = result.data;
		weighing.targetWeight = data.actualWeight;
		weighing.theoreticalWeight = data.theoreticalWeight;

		$('#theoreQuantity').text(weighing.theoreticalWeight);
		$('#countQuantity').text(weighing.targetWeight);
	});
}
/*--------------------------------------------------打印称量标签--------------------------------------------------------*/
//称量标签打印方法
function PrintWHLabel(resultId,sid){
	var PrintLabelPath = serverPath + "weighing/weighingTag";
	var resultInfo = getWHresult();
	var datas = {
		"id" : resultId,
		"sid" : sid
	};
	ibcpAjax.Select(PrintLabelPath, datas, true, function(result){
		alert(JSON.stringify(result.data));
		jsObj.printWeighLabel(JSON.stringify(result.data));
	});
}

//获取称量结果id
function getWHresult(){
	'use srict';
	return 2;
}